/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.applicationResource;

import com.blandware.atleap.common.util.Folder;
import com.blandware.atleap.common.util.FolderList;
import com.blandware.atleap.common.util.RegExUtil;
import com.blandware.atleap.webapp.action.core.grid.BaseGridAction;
import com.blandware.atleap.webapp.util.core.ApplicationResources;
import com.blandware.atleap.webapp.util.core.VirtualFolder;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * <p>Forward to the page with list of action pages
 * </p>
 * <p><a href="ListApplicationResourcesAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.8 $ $Date: 2007/12/18 18:15:09 $
 * @struts.action path="/core/applicationResource/list"
 * name="applicationResourceForm"
 * validate="false"
 * roles="core-applicationResource-list"
 * @struts.action-forward name="listApplicationResources"
 * path=".core.applicationResource.list"
 */
public final class ListApplicationResourcesAction extends BaseGridAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		String currentFolder = "";
		if ( request.getParameter("currentFolder") != null ) {
			currentFolder = request.getParameter("currentFolder");
			request.getSession().setAttribute(WebappConstants.APPLICATION_RESOURCES_CURRENT_PATH_KEY, currentFolder);
		} else if ( request.getSession().getAttribute(WebappConstants.APPLICATION_RESOURCES_CURRENT_PATH_KEY) != null ) {
			currentFolder = (String) request.getSession().getAttribute(WebappConstants.APPLICATION_RESOURCES_CURRENT_PATH_KEY);
		}

		if ( currentFolder == null ) {
			currentFolder = "";
		}

		ApplicationResources applicationResources = ApplicationResources.getInstance(servlet.getServletContext());

		// algorithm used to extract folders from set of keys:
		// 1. if key contains more than one dot after entry of current folder, sequence of symbols between first
		//    and second dots will be recognized as folder name
		// 2. if key contains only one dot after entry of current folder, it will be recognized as key in current folder
		// 3. if key does not start with current folder, it will be skipped

		// ensure, that current folder does not end with dot
		if ( currentFolder.length() > 0 && currentFolder.endsWith(".") ) {
			currentFolder = currentFolder.substring(0, currentFolder.length() - 1);
		}

		// pattern to determine whether or not we have an additional folder
		// if current folder is not an empty string, key must start from it and have at least two dots
		// otherwise one dot is enough
		String folderPatternString = "";
		if ( currentFolder.length() > 0 ) {
			folderPatternString = "(" + RegExUtil.escapeMetasymbols(currentFolder) + ")\\.";
		}
		folderPatternString += "([^\\.]+)(\\.[^\\.]+)+";

		// patter to determine, whether or not we have key
		// if current folder is not an empty string, key must start from it and have at least one dot
		// otherwise, no dot is required
		String keyPatternString = "";
		if ( currentFolder.length() > 0 ) {
			keyPatternString = "(" + RegExUtil.escapeMetasymbols(currentFolder) + ")\\.";
		}
		keyPatternString += "([^\\.]+)";

		// pattern compiler instance to use
		PatternCompiler compiler = new Perl5Compiler();

		// compiled patterns
		Pattern folderPattern = compiler.compile(folderPatternString);
		Pattern keyPattern = compiler.compile(keyPatternString);

		// pattern matcher instance to use
		PatternMatcher matcher = new Perl5Matcher();

		// list of folders
		SortedSet folderSet = new TreeSet();

		// list of keys
		List keys = new ArrayList(applicationResources.getKeys());

		for ( Iterator i = keys.iterator(); i.hasNext(); ) {
			String key = (String) i.next();

			// check folder name
			if ( matcher.matches(key, folderPattern) ) {
				MatchResult result = matcher.getMatch();

				// according to pattern, if current folder is not an empty string, folder name is in second group
				// otherwise it is in the first group;
				String folderName = currentFolder.length() > 0 ? result.group(2) : result.group(1);
				Folder folder = new VirtualFolder(folderName, currentFolder, '.');
				folderSet.add(folder);

				// remove this key from list
				i.remove();
			} else if ( !matcher.matches(key, keyPattern) ) {
				// remove key, because it is placed outside of current folder
				i.remove();
			}
		}

		// create parent folder if current folder is not the root folder
		Folder parentFolder = null;
		if ( currentFolder.length() > 0 ) {
			int k = currentFolder.lastIndexOf(".");
			if ( k < 0 ) {
				k = 0;
			}
			String parentFolderPath = currentFolder.substring(0, k);
			parentFolder = new VirtualFolder("..", parentFolderPath, '.', true);
		}

		LinkedList folders = new LinkedList(folderSet);
		if ( parentFolder != null ) {
			folders.addFirst(parentFolder);
		}

		request.setAttribute(WebappConstants.APPLICATION_RESOURCES_COLLECTION_KEY, keys);
		request.setAttribute(WebappConstants.FOLDERS_COLLECTION_KEY, folders);
		request.setAttribute(WebappConstants.CURRENT_PATH_KEY, new FolderList(VirtualFolder.splitPath(currentFolder, '.', false), '.'));

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("listApplicationResources");
	}
}